package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.model.SysRoleAcl;
import com.example.demo.dao.SysRoleAclMapper;
import com.example.demo.requesthandler.UserSession;
import com.example.demo.service.ISysRoleAclService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.util.IpAddressUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Webgasd
 * @since 2021-04-26
 */
@Service
public class SysRoleAclServiceImpl extends ServiceImpl<SysRoleAclMapper, SysRoleAcl> implements ISysRoleAclService {
    @Autowired
    private SysRoleAclMapper sysRoleAclMapper;

    /**
     * 修改某一角色的模块权限
     *
     * @param roleId
     * @param aclIdList
     */
    @Override
    public int changeRoleAcl(Integer roleId, List<Integer> aclIdList) {
        List<Integer> originAclIdList = sysRoleAclMapper.getAclIdListByRoleIdList(Lists.newArrayList(roleId));
        if (originAclIdList.size() == aclIdList.size()) {
            Set<Integer> originAclIdSet = Sets.newHashSet(originAclIdList);
            Set<Integer> aclIdSet = Sets.newHashSet(aclIdList);
            originAclIdSet.removeAll(aclIdSet);
            if (CollectionUtils.isEmpty(originAclIdSet)) {
                return 0;
            }
        }
        return updateRoleAcl(roleId, aclIdList);
    }

    public int updateRoleAcl(Integer roleId, List<Integer> aclIdList) {
        QueryWrapper<SysRoleAcl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(roleId != null, "role_id", roleId);
        sysRoleAclMapper.delete(queryWrapper);
        if (CollectionUtils.isEmpty(aclIdList)) {
            return 0;
        }
        List<SysRoleAcl> roleAclList = Lists.newArrayList();
        for (Integer aclId : aclIdList) {
            SysRoleAcl roleAcl = new SysRoleAcl();
            roleAcl.setRoleId(roleId);
            roleAcl.setAclId(aclId);
            roleAcl.setOperator(UserSession.getLoginName());
            roleAcl.setOperateIp(IpAddressUtil.getRemoteIp());
            roleAcl.setOperateTime(new Date());
            roleAclList.add(roleAcl);
        }
        return sysRoleAclMapper.batchInsert(roleAclList);
    }
}
